const db = require('../tools/mongodb');
const db_config = require('../jd/mongodb.config');
const dalay = require('../tools/delay');

let repeat = async function (attampt) {
    return new Promise((res,rej)=>{
        try {
            //await dalay(2000);
            const mongo = db_config.jd.config;
            db.find(mongo, { name: "retry" }).then(found=>{
                let config = found[0]
               // _try(config.retry, config.wait);
                return new Promise(async (resolve, reject) => {
                    let c = 0;
                    while (true) {
                        try {
                            let t = await attampt;
                            resolve(t);
                            break;
                        }
                        catch (error) {
                            console.log(error);
                            if (c < config.retry - 1) {
                                c++;
                                console.log(`发生错误，将于${config.wait}秒后重试！`)
                                await dalay(config.wait*1000);
                                continue;
                            }
                            else {
                                reject(error);
                                break;
                            }
                        }
                    }
                })
            }).then(r=>res(r)).catch(r=>{rej( `已超过重试次数!`);});
        }
        catch (error) {
            //写入数据库
            rej(error);
        }
    });
}
module.exports = repeat;
